package medicalDocumentation.medicalRepository;

import entity.ClinicalPathway;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class ClinicalPathwayRepositorySessionBean implements ClinicalPathwayRepositorySessionBeanRemote {

    public final String CLINICAL_PATHWAY_CONDITION_REQUIRED = "Clinical pathway condition required";
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public String addClinicalPathway(String clinicalPathwayCondition, String clinicalPathwayName, String clinicalPathwayDetail, String remark) {
        if (clinicalPathwayCondition == null) {
            return CLINICAL_PATHWAY_CONDITION_REQUIRED;
        }
        ClinicalPathway clinicalPathway = new ClinicalPathway();
        clinicalPathway.setClinicalPathwayName(clinicalPathwayName);
        clinicalPathway.setClinicalPathwayCondition(clinicalPathwayCondition);
        clinicalPathway.setClinicalPathwayDetail(clinicalPathwayDetail);
        clinicalPathway.setRemark(remark);
        entityManager.persist(clinicalPathway);
        entityManager.flush();
        return String.valueOf(clinicalPathway.getId());
    }

    @Override
    public List<ClinicalPathway> getClinicalPathwayById(String id) {
        if(id == null)
            return null;
        String strQuery = "SELECT m FROM ClinicalPathway m WHERE m.id = :inId";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inId", Long.valueOf(id));
        return query.getResultList();
    }

    @Override
    public List<ClinicalPathway> getAllClinicalPathway() {
        String strQuery = "SELECT m FROM ClinicalPathway m";
        Query query = entityManager.createQuery(strQuery);
        return query.getResultList();
    }

    @Override
    public void deleteClinicalPathway(String id) {
        List clinicalPathways = getClinicalPathwayById(id);
        if (clinicalPathways.get(0) != null) {
            entityManager.remove(clinicalPathways.get(0));
            entityManager.flush();
        }
    }

    @Override
    public void updateClinicalPathway(String id, String clinicalPathwayName, String clinicalPathwayCondition, String clinicalPathwayDetail, String remark) {
        ClinicalPathway clinicalPathway = getClinicalPathwayById(id).get(0);
        if (clinicalPathway != null) {
            clinicalPathway.setClinicalPathwayName(clinicalPathwayName);
            clinicalPathway.setClinicalPathwayCondition(clinicalPathwayCondition);
            clinicalPathway.setClinicalPathwayDetail(clinicalPathwayDetail);
            clinicalPathway.setRemark(remark);
            entityManager.merge(clinicalPathway);
            entityManager.flush();
        }
    }
}
